package chapter2.No2_2_synchronized同步语句块.l多线程的死锁.demo2;

/**
 * 用代码块模拟死锁
 *
 * @author liujian
 * @version 2016/11/14 0014
 */
public class MyThread implements Runnable {

    Object obj1 = new Object();
    Object obj2 = new Object();

    public MyThread() {
        new Thread(this).start();
        doTest();
    }

    public static void main(String[] args) {
        new MyThread();
    }

    public void run() {
        synchronized (obj1) {
            System.out.println(Thread.currentThread().getName() + " 得到obj1对象锁");
            try {
                Thread.sleep(1000);
                synchronized (obj2) {
                    System.out.println(Thread.currentThread().getName() + " 得到obj2对象锁");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void doTest() {
        synchronized (obj2) {
            System.out.println(Thread.currentThread().getName() + " 得到obj2对象锁");
            try {
                Thread.sleep(1000);
                synchronized (obj1) {
                    System.out.println(Thread.currentThread().getName()+" 得到obj1对象锁");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
